package so.sao.shop.supplier.service.authorized.impl;

import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import net.sf.json.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import so.sao.shop.supplier.dao.authorized.PermissionDao;
import so.sao.shop.supplier.dao.authorized.RoleDao;
import so.sao.shop.supplier.dao.authorized.RolePermissionDao;
import so.sao.shop.supplier.domain.authorized.Permission;
import so.sao.shop.supplier.domain.authorized.Role;
import so.sao.shop.supplier.domain.authorized.RolePermission;
import so.sao.shop.supplier.domain.authorized.UserRoles;
import so.sao.shop.supplier.pojo.Result;
import so.sao.shop.supplier.pojo.input.authorized.RoleInput;
import so.sao.shop.supplier.pojo.output.authorized.RoleOut;
import so.sao.shop.supplier.service.authorized.RoleService;
import so.sao.shop.supplier.util.PageTool;

import java.util.*;

/**
 * @author tengfei.zhang
 * @Title: RoleServiceImpl
 * 角色权限业务实现
 * @create 2017-10-25 8:56
 **/
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> save(RoleInput roleInput) {
        Role roles = roleDao.findByRoleName(roleInput.getName(),roleInput.getOperatorId());
        if(roles != null){
            return Result.fail("角色名称已经存在");
        }
        if(roleInput.getPermissionsIds() == null || (roleInput.getPermissionsIds() != null && roleInput.getPermissionsIds().length == 0)){
            return Result.fail("权限不能为空");
        }
        //初始化角色
        Role role = new Role();
        //将角色入参对象复制到角色对象
        BeanUtils.copyProperties(roleInput,role);
        //插入角色信息
        roleDao.save(role);
        //获取角色权限id
        Long[] permissionsIds = roleInput.getPermissionsIds();
        //插入角色权限中间表
        saveRolePermissions(permissionsIds, role.getId());
        return Result.success("插入角色成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> update(RoleInput roleInput) {
        Role roles = roleDao.findByRoleName(roleInput.getName(),roleInput.getOperatorId());
        if(roles != null && !roles.getId().equals(roleInput.getId())){
            return Result.fail("角色名称已经存在");
        }
        if(roleInput.getPermissionsIds() == null || (roleInput.getPermissionsIds() != null && roleInput.getPermissionsIds().length == 0)){
            return Result.fail("权限不能为空");
        }
        rolePermissionDao.deleteById(roleInput.getId());
        //初始化角色
        Role role = new Role();
        //将角色入参对象复制到角色对象
        BeanUtils.copyProperties(roleInput,role);
        role.setUpdateTime(new Date());
        //插入角色
        roleDao.update(role);
        //获取角色权限id
        Long[] permissionsIds = roleInput.getPermissionsIds();
        //插入角色权限信息
        saveRolePermissions(permissionsIds, roleInput.getId());
        return Result.success("更新角色成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteById(Long id) {
        //根据角色id判断是否有用户使用此角色有用户使用返回给前端不能更新否则删除
        List<UserRoles> userRoles = roleDao.findByRoleId(id);
        if(!userRoles.isEmpty()&&userRoles.size()!=0){
            return Result.fail("该角色正在使用，不能删除");
        }
        rolePermissionDao.deleteById(id);
        roleDao.deleteById(id);
        return Result.success("删除角色成功");
    }

    @Override
    public Result<?> searchRoles(RoleInput roleInput) {
        PageTool.startPage(roleInput.getPageNum(),roleInput.getPageSize());
        List<RoleOut> roles = roleDao.findPage(roleInput.getUserId());
        PageInfo<RoleOut> pageInfo = new PageInfo<RoleOut>(roles);
        return Result.success("查询角色成功",pageInfo);
    }

    @Override
    public Result<?> findById(Long roleId) {
        Role role = roleDao.findById(roleId);
        //List<Long> permissionList = roleDao.findRoleId(roleId);
        //return Result.success("查询权限id成功",new RoleOut(role.getId(),role.getName(),permissionList));

        List<Permission> permissions = permissionDao.findByRoleId(roleId);
        List<Long> permissionIds = this.filterRouteIds(permissions);
        return Result.success("查询权限id成功", new RoleOut(role.getId(), role.getName(), permissionIds));
    }

    /**
     * 转换对象为一个routeUrl列表，并且移除所有叶子结点的父节点
     *
     * @param permissions
     * @return
     */
    private List<Long> filterRouteIds(List<Permission> permissions) {
        List<Long> permissionIds = new ArrayList<>();
        List<Permission> allPermissions = new ArrayList<Permission>(permissions);
        List<Permission> leafPermissions = new ArrayList<Permission>(permissions);
        List<Permission> modifPermissions = new ArrayList<Permission>();

        for (Permission parentPermission : allPermissions) {
            for (Permission childrenermission : allPermissions) {
                if (parentPermission.getId().equals(childrenermission.getParentId())) {
                    modifPermissions.add(parentPermission);
                    continue;
                }
            }
            leafPermissions.removeAll(modifPermissions);
        }

        for (Permission childrenPermission : leafPermissions) {
            permissionIds.add(childrenPermission.getId());
        }
        return permissionIds;
    }

    /**
     * 插入角色权限中间表
     *
     * @param permissionsIds
     * @param id2
     */
    public void saveRolePermissions(Long[] permissionsIds, Long id2) {
        List<Long> ids = Arrays.asList(permissionsIds);
        List<RolePermission> rolePermissions = new ArrayList<RolePermission>();
        RolePermission rolePermission = null;
        for (Long id : ids) {
            rolePermission = new RolePermission();
            rolePermission.setRoleId(id2);
            rolePermission.setPermissionId(id);
            rolePermissions.add(rolePermission);
        }
        rolePermissionDao.save(rolePermissions);
    }

    @Override
    public List<RoleOut> searchAllRole(Long loginUserId) {
        Map<String,Object> roleMap = new HashMap<String,Object>();
        roleMap.put("operatorId",loginUserId);
        roleMap.put("ignore",true);
        List<RoleOut> roles = roleDao.findAll(roleMap);
        return roles;
    }
}
